package com.ruoyi.utils.wwx;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.utils.json.JsonUtils;
import com.ruoyi.wwxkf.domain.WxMsgRevice;
import com.ruoyi.wwxkf.vo.WwxSyncMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 企业微信的网络请求
 */
@Component
@Slf4j
public class WwxNetWorkUtil {

    /**
     * 微信客服接口请求网关
     */
    private static String baseUrl = "https://qyapi.weixin.qq.com/cgi-bin";
    private static String corpid = "ww381c803ff4e460b9";
    private static String corpsecret = "QPylR2qmkLATFzMkz7RBG5FJlswVvFLUhA7SfsSSUjs";

    /**
     * 获取token
     *
     * @return
     */
    public static String getAccessToken() {
        // 动态获取当前方法名称
        String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
        try {
            String resultStr = HttpUtil.get(baseUrl + "/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret);
            //校验错误
            errorCatch(resultStr, methodName);
            String access_token = JsonUtils.parseMiddleData(resultStr, "access_token");
            log.error("生成的access_token:{}", access_token);
            return access_token;
        } catch (Exception e) {
            log.error("企业微信网络请求方法【{}】请求错误", methodName);
            throw new RuntimeException(e.getMessage());
        }
    }


    /**
     * 获取用户发送的具体消息
     * https://developer.work.weixin.qq.com/document/path/96426#%E5%9B%9E%E8%B0%83%E4%BA%8B%E4%BB%B6  参考文档
     *
     * @param token
     * @param wxMsgRevice
     * @return
     */
    public static WwxSyncMsg syncMsg(String token, WxMsgRevice wxMsgRevice, String cursor,Integer origin) {

        // 动态获取当前方法名称
        String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
        try {
            long createTime = wxMsgRevice.getCreateTime();
            String openKfId = wxMsgRevice.getOpenKfId();
            String tokenMsg = wxMsgRevice.getToken();
            if (StrUtil.isBlank(openKfId)) {
                log.error("方法:{}中,openKfId为空", methodName);
            }
            HashMap<Object, Object> bodyParam = new HashMap<>();
            bodyParam.put("open_kfid", openKfId);
            bodyParam.put("token", tokenMsg);
            if (StrUtil.isNotBlank(cursor)) {
                bodyParam.put("cursor", cursor);
            }
            //使用hutool请求接口
            String bodyParamString = JSONObject.toJSONString(bodyParam);
            //链式构建请求
            String resultStr = HttpRequest.post(baseUrl + "/kf/sync_msg?access_token=" + token)
                    .header("Content-Type", "application/json")
                    .body(bodyParamString)//表单内容
                    .timeout(20000)//超时，毫秒
                    .execute().body();

            //校验错误
            errorCatch(resultStr, methodName);
            String next_cursor = JsonUtils.parseMiddleData(resultStr, "next_cursor");
            String msg_list = JsonUtils.parseMiddleData(resultStr, "msg_list");
            //消息列表
            List<WwxSyncMsg> wwxSyncMsgs = JSONArray.parseArray(msg_list, WwxSyncMsg.class);
            WwxSyncMsg wwxSyncMsg = catchSyncMsgRsutl(createTime, openKfId, wwxSyncMsgs,origin);
            wwxSyncMsg.setCursor(next_cursor);
            return wwxSyncMsg;
        } catch (Exception e) {
            log.error("企业微信网络请求方法【{}】请求错误", methodName);
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 发送消息给用户
     * https://developer.work.weixin.qq.com/document/path/96426#%E5%9B%9E%E8%B0%83%E4%BA%8B%E4%BB%B6  参考文档
     *
     * @param token
     * @param wwxSyncMsg
     * @return
     */
    public static void sendMsgText(String token, WwxSyncMsg wwxSyncMsg,String replayContent ) {

        // 动态获取当前方法名称
        String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
        try {
            //消息体
            String content = wwxSyncMsg.getText().getContent();
            if (StrUtil.isNotBlank(content)){
                HashMap<Object, Object> bodyParam = new HashMap<>();
                bodyParam.put("touser", wwxSyncMsg.getExternal_userid());
                bodyParam.put("open_kfid", wwxSyncMsg.getOpen_kfid());
//                bodyParam.put("msgid", wwxSyncMsg.getMsgid());
                bodyParam.put("msgtype", "text");

                Map<String, String> textMap = new HashMap<>();
                textMap.put("content",replayContent);
                bodyParam.put("text", textMap);

                //使用hutool请求接口
                String bodyParamString = JSONObject.toJSONString(bodyParam);
                //链式构建请求
                String resultStr = HttpRequest.post(baseUrl + "/kf/send_msg?access_token=" + token)
                        .header("Content-Type", "application/json")
                        .body(bodyParamString)//表单内容
                        .timeout(20000)//超时，毫秒
                        .execute().body();
                //校验错误
                errorCatch(resultStr, methodName);
                String errmsg = JsonUtils.parseMiddleData(resultStr, "errmsg");
                log.info("客服【{}】,回复消息成功：{}",wwxSyncMsg.getOpen_kfid(),errmsg);
            }

        } catch (Exception e) {
            log.error("企业微信网络请求方法【{}】请求错误", methodName);
            throw new RuntimeException(e.getMessage());
        }
    }



    /**
     * 获客链接消息
     * https://developer.work.weixin.qq.com/document/path/96426#%E5%9B%9E%E8%B0%83%E4%BA%8B%E4%BB%B6  参考文档
     *
     * @param token
     * @param wwxSyncMsg
     * @return
     */
    public static void sendMsgGetCustom(String token, WwxSyncMsg wwxSyncMsg,String linkurl) {

        // 动态获取当前方法名称
        String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
        try {
            //消息体
            String content = wwxSyncMsg.getText().getContent();
            if (StrUtil.isNotBlank(content)){
                HashMap<Object, Object> bodyParam = new HashMap<>();
                bodyParam.put("touser", wwxSyncMsg.getExternal_userid());
                bodyParam.put("open_kfid", wwxSyncMsg.getOpen_kfid());
                bodyParam.put("msgtype", "ca_link");

                Map<String, String> textMap = new HashMap<>();
                textMap.put("link_url",linkurl);
                bodyParam.put("ca_link", textMap);

                //使用hutool请求接口
                String bodyParamString = JSONObject.toJSONString(bodyParam);
                //链式构建请求
                String resultStr = HttpRequest.post(baseUrl + "/kf/send_msg?access_token=" + token)
                        .header("Content-Type", "application/json")
                        .body(bodyParamString)//表单内容
                        .timeout(20000)//超时，毫秒
                        .execute().body();
                //校验错误
                errorCatch(resultStr, methodName);
                String errmsg = JsonUtils.parseMiddleData(resultStr, "errmsg");
                log.info("客服【{}】,回复【获客消息】消息成功：{}",wwxSyncMsg.getOpen_kfid(),errmsg);
            }

        } catch (Exception e) {
            log.error("企业微信网络请求方法【{}】请求错误", methodName);
            throw new RuntimeException(e.getMessage());
        }
    }
    /**
     * 对消息体进行校验
     *
     * @param returnMsg    微信方法返回的信息
     * @param functionName 执行的方法名称
     */
    public static void errorCatch(String returnMsg, String functionName) {
        Map<String, String> errorMap = getErrorMap();
        String errcode = JsonUtils.parseMiddleData(returnMsg, "errcode");
        if (StrUtil.equals(errcode, "0")) {
            return;
        }
        String errorMessage = errorMap.get(errcode);
        if (errorMessage != null) {
            log.error("企业微信网络请求方法【{}】请求错误, 错误原因：{}", functionName, errorMessage);
            throw new RuntimeException(errorMessage);
        }

        log.error("企业微信网络请求方法【{}】请求错误, 报文全文：{}", functionName, returnMsg);
        throw new RuntimeException("微信请求解析错误");
    }


    public static WwxSyncMsg catchSyncMsgRsutl(long send_time, String openKfid, List<WwxSyncMsg> wwxSyncMsgs,Integer origin) {

        Optional<WwxSyncMsg> result = wwxSyncMsgs.stream()
                .filter(msg -> msg.getSend_time() == send_time && msg.getOpen_kfid().equals(openKfid) && msg.getOrigin() == origin) // 筛选条件
                .max(Comparator.comparingLong(WwxSyncMsg::getSend_time)); // 获取 send_time 最大的一条

        // 判断是否找到符合条件的记录
        if (result.isPresent()) {
            WwxSyncMsg targetMsg = result.get();
            log.info("方法【catchSyncMsgRsutl】找到符合条件的记录消息: " + targetMsg);
            return targetMsg;
        } else {
            return null;
        }
    }


    /**
     * 获取错误映射
     *
     * @return
     */
    public static Map<String, String> getErrorMap() {
        return new HashMap<>();
    }

}
